'use strict';

const Service = require('egg').Service;
const sequelize = require('sequelize')
const { Op } = require('sequelize').Sequelize;

class SuggestService extends Service {

    async add(request) {
        let { content } = request;
        const { Suggest } = this.ctx.model;

        let suggest = {
            content,
            author: this.ctx.state.user.id,
            createDate: new Date(),
            createBy: this.ctx.state.user.id
        }

        const retSuggest = await Suggest.create(suggest);

        return {
            result: true
        }
    }

    async list(pageNo, pageSize) {
        const offset = pageSize * (pageNo - 1);
        const limit = pageSize;

        const { id} = this.ctx.query;

        let sql = 'SELECT b.id, b.content, b.author userId, u.nick_name nickName, '
        sql += ' b.create_date createDate FROM suggest b '
        sql += 'left join user u on u.id = b.author where';
        if (id) sql += ` b.id = ${id}`;
        if (!id) sql = sql.replace('where', '')
        sql+=" order by b.create_date desc"
        const suggests = await this.ctx.model.query(sql, { type: sequelize.QueryTypes.SELECT });

        let hasNextPage = pageNo * pageSize < suggests.length;

        let result = {
            totalCount: suggests.length,
            pageNo,
            pageSize,
            suggests: suggests.splice(offset, limit),
            hasNextPage,
        };
        return result;
    }


    async delete(id) {
        const { Suggest} = this.ctx.model;
        await Suggest.destroy({
            where: {
                id
            }
        });

        return {
            result: true
        };

    }
}
module.exports = SuggestService;
